﻿using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Loyalty.Infrastructure.EntityFramework.Poco;
using Loyalty.Application;
using Loyalty.Core.Entities;
using Loyalty.Infrastructure.EntityFramework.Repositories;
using Loyalty.Infrastructure.EntityFramework.Interfaces;


namespace Loyalty.UI.Infrastructure
{
    public class DbServiceLayer
    {
        private readonly IUnitOfWork _unitOfWork;

        public DbServiceLayer(IUnitOfWork work)
        {
            _unitOfWork = work;
        }

        public ErrorExeptionsResult SaveChanges()
        {
            ErrorExeptionsResult ret = new ErrorExeptionsResult();
            try
            {
                _unitOfWork.SaveChanges();
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null && ex.InnerException.HResult == -2146233087)
                {
                    List<string> EntityName = new List<string>();
                    var message = ex.InnerException.InnerException.Message;
                    const string pattern = "\"dbo.([A-Za-z0-9]*)";
                    var tablesName = Regex.Matches(message, pattern);
                    if (tablesName.Count > 0)
                    {
                        for (int i = 0; i < tablesName.Count; i++)
                        {
                            if (tablesName[i].Success)
                            {
                                EntityName.Add(tablesName[i].Value.Replace("\"dbo.", ""));
                            }
                        }
                    }

                    //var _IDD_FormService = StructureMap.ObjectFactory.GetInstance<IDD_FormService>();
                    //var captions = new List<string>();

                    //foreach (var formName in EntityName)
                    //{
                    //    string FormCaption =
                    //        _IDD_FormService.GetAll(
                    //            new DD_Form
                    //                {
                    //                    FormGUID =
                    //                        String.Format("RestaurantApp.Web.Areas.Backend.Controllers.{0}Controller",
                    //                                      formName).GetGUID().ToString()
                    //                }, null)
                    //                        .CurrentItems.FirstOrDefault()
                    //                        .FormCaption;
                    //    captions.Add(FormCaption);
                    //}

                    //var friendlyMessage = "رکوردهای وابسته به این رکورد در فرم {0} را حذف کنید.";
                    //string forms = captions.Aggregate("", (current, item) => current + item);

                    //friendlyMessage = String.Format(friendlyMessage, forms);

                    //ret.ErrorMessage = friendlyMessage;
                    //ret.RequestState = RequestStates.Fail;

                    //if(ex.InnerException.Message.Contains())
                }
                else
                {
                    try
                    {
                        ret.ErrorMessage = ex.Message + " " + ex.InnerException.Message;
                        ret.RequestState = RequestStates.Fail;
                    }
                    catch
                    {
                        ret.ErrorMessage = ex.Message;
                    }

                }
                if (ret.ErrorMessage == null)
                    ret.ErrorMessage = "";
                ret.ErrorMessage += "عملیات انجام نشد";
                ret.RequestState = RequestStates.Fail;
            }
            return ret;
        }

                
        #region CityRepository

        public ErrorExeptionsResult<City> City_Add(City Entity, ICityRepository _ICityRepository)
        {
            var _return = new ErrorExeptionsResult<City>();
            try
            {

                var ret = _ICityRepository.Add(Entity);
                if (ret.RequestState == RequestStates.Successfull)
                {
                    var temp = SaveChanges();
                    _return.RequestState = temp.RequestState;
                    _return.ErrorMessage = temp.ErrorMessage;
                    if (ret.RequestState == RequestStates.Successfull)
                    {
                        _return.SelectedItem = _ICityRepository.Get(Entity.Id).SelectedItem;
                    }
                }
                return _return;
            }
            catch (Exception ex)
            {
                _return.ErrorMessage = ex.Message;
                _return.RequestState = RequestStates.Fail;
                return _return;
            }
        }

        public ErrorExeptionsResult<City> City_Edit(City Entity, ICityRepository _ICityRepository)
        {
            var _return = new ErrorExeptionsResult<City>();

            try
            {
                var ret = _ICityRepository.Edit(Entity);
                if (ret.RequestState == RequestStates.Successfull)
                {
                    var temp = SaveChanges();
                    _return.RequestState = temp.RequestState;
                    _return.ErrorMessage = temp.ErrorMessage;
                    if (ret.RequestState == RequestStates.Successfull)
                    {
                        _return.SelectedItem = _ICityRepository.Get(Entity.Id).SelectedItem;
                    }
                }
                return _return;
            }
            catch (Exception ex)
            {
                var ret = new ErrorExeptionsResult<City>();
                _return.ErrorMessage = ex.Message;
                _return.RequestState = RequestStates.Fail;
                return _return;
            }
        }

        public ErrorExeptionsResult<City> City_Delete(City Entity, ICityRepository _ICityRepository)
        {
            var _return = new ErrorExeptionsResult<City>();

            try
            {
                var getRecord = _ICityRepository.Delete(Entity);
                if (getRecord.RequestState == RequestStates.Successfull)
                {
                    var temp = SaveChanges();
                    _return.SelectedItem = getRecord.SelectedItem;
                    _return.RequestState = temp.RequestState;
                    _return.ErrorMessage = temp.ErrorMessage;
                }
                return _return;
            }
            catch (Exception ex)
            {
                _return.ErrorMessage = ex.Message;
                _return.RequestState = RequestStates.Fail;
                return _return;
            }
        }

        public ErrorExeptionsResult<City> City_GetAll(City SearchOptions, int? PageNumber, int? RowPerPage, DynamicSearchEngine Filters, ICityRepository _ICityRepository)
        {
            var _return = new ErrorExeptionsResult<City>();
            try
            {
                _return = _ICityRepository.GetAll(SearchOptions, PageNumber, RowPerPage, Filters);
                return _return;
            }
            catch (Exception ex)
            {
                _return.ErrorMessage = ex.Message;
                _return.RequestState = RequestStates.Fail;
                return _return;
            }
        }

        public ErrorExeptionsResult<City> City_Get(long? id, ICityRepository _ICityRepository)
        {
            var _return = new ErrorExeptionsResult<City>();
            try
            {
                _return = _ICityRepository.Get(id);
                return _return;
            }
            catch (Exception ex)
            {
                _return.ErrorMessage = ex.Message;
                _return.RequestState = RequestStates.Fail;
                return _return;
            }
        }

        #endregion

        
    }
}